const ctx = exports.ctx;
const utils = exports.utils;
const http = utils.getHttp()
const isMobile = utils.getDevice() === 'mobile'

function debounce(func, delay = 300) {
    let timer = null;
    return function(...args) {
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        timer = setTimeout(function() {
            func.apply(this, args);
        }, delay);
    }

}
export const ocrinvoice = {
    template: `
  <div>
    <div style="text-align:center">
      <template v-if="pageStatus === 2">
        <a-spin v-if="!isMobile" :spinning="isLoading">
          <a-button type="primary"  @click="debounceBtn">发票自动识别</a-button>
        </a-spin>
        <van-button v-else type="primary" @click="debounceBtn" :loading="isLoading">发票自动识别</van-button>
      </template>
      <div v-else>发票自动识别</div>
    </div>  
  </div>
  `,
    props: ['instance', 'name', 'value', 'rowIndex', 'pageStatus'],
    emits: ['change'],
    data: function() {
        return {
            isMobile: isMobile,
            isLoading: false,
        };
    },
    mounted: function() {
        // this.reverseMessage()
        // this.$emit('change', 777)//用于更新数据
    },
    methods: {
        debounceBtn() {
            debounce(this.checkInvoice())
        },

        checkInvoice: function() {
            const pic = ctx.getState('O4bzvp6avG', this.rowIndex) //明细表文件
            const index = this.rowIndex; //当前点击行index
            const item = pic[0] //当前点击行文件id
                // const mess = "第" + (index + 1) + "行发票验真失败,可手动填写"
                // if (item === undefined) return;

            this.isLoading = true
            const axios = http.getAxios()
            axios.request({
                url: '../../attachment/api/v1/private/download/' + item,
                responseType: "arraybuffer"
            }).then(result => {
                utils.querySvc({
                        "app_id": "transcosmos_app_5l5q1lrjbd",
                        "svc_code": "ocr_v2_new",
                        "save_datas": {
                            "nsrsbh": '201609140000001',
                            "orgcode": '20160914001',
                            "file": btoa(new Uint8Array(result.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
                        }
                    }).then(res => {
                        if (res.code == "000000") {
                            // 处理数据结构
                            const newRows = res.data.map((dyz_item) => ({
                                    Tye8Alzsqx: dyz_item.fpHm,
                                    Mb9qU0g9gN: dyz_item.kprqNew == 0 ? '' : dyz_item.kprqNew,
                                    vkaL98XlbX: dyz_item.jshj,
                                    wYWF6ENSpD: dyz_item.gmfNsrsbh,
                                    RE5hD0qSPW: dyz_item.items[0].sl,
                                    zDqAbRxpxM: dyz_item.xsfMc,
                                    O4bzvp6avG: JSON.parse(JSON.stringify(pic))
                                }))
                                // 当前点击行index + 发票res长度
                            const len = this.rowIndex + newRows.length
                            console.log(newRows, ...newRows, 'newRows')
                                //删除当前操作空行-设置发票res数据（赋值操作）
                            ctx.getState('cjJWdFuXdh').splice(this.rowIndex, 1, ...newRows)
                                // 遍历最新发票res，发票号码为空==验真失败
                            for (let i = this.rowIndex; i < len; i++) {
                                // 验真过禁止再次验真，设置只读
                                ctx.setInstance('edU0O1zTSu', 'defaultState', 'readonly', i)
                                const fpHm = newRows[i - this.rowIndex].Tye8Alzsqx
                                if (!fpHm) {
                                    utils.toast("第" + (i + 1) + "行发票验真失败,可手动填写", 'warning')
                                        // 设置验真失败明细行为可输入
                                    setTimeout(() => {
                                        ctx.setInstance('Tye8Alzsqx', 'defaultState', 'default', i)
                                        ctx.setInstance('vkaL98XlbX', 'defaultState', 'default', i)
                                        ctx.setInstance('wYWF6ENSpD', 'defaultState', 'default', i)
                                        ctx.setInstance('RE5hD0qSPW', 'defaultState', 'default', i)
                                        ctx.setInstance('zDqAbRxpxM', 'defaultState', 'default', i)
                                        ctx.setInstance('Mb9qU0g9gN', 'defaultState', 'default', i)
                                    }, 200)
                                }
                            }
                            this.isLoading = false
                        } else {
                            utils.toast(res.message, 'error')
                            this.isLoading = false
                        }
                    }).catch(() => {
                        utils.toast('发票过大，请重新上传', 'error')
                        this.isLoading = false
                        console.log('error')
                    })
                    // ctx.setState('Tye8Alzsqx', dyz_item.fpHm, dyz_index)//发票号码 Tye8Alzsqx
                    // ctx.setState('gHqfqLwbuK', dyz_item.kprqNew, dyz_index)//开票日期 Mb9qU0g9gN
                    // ctx.setState('vkaL98XlbX', Number(dyz_item.jshj), dyz_index)//开票金额 vkaL98XlbX
                    // ctx.setState('wYWF6ENSpD', dyz_item.gmfNsrsbh, dyz_index)//税号 wYWF6ENSpD
                    // ctx.setState('RE5hD0qSPW', Number(dyz_item.items[0].sl), dyz_index)//税率 RE5hD0qSPW
                    // ctx.setState('zDqAbRxpxM', dyz_item.xsfMc, dyz_index)//销售方公司 zDqAbRxpxM
            })
        }
    }
}